package math;

import common.AltaRicaModelManager;
import common.AltaRicaModel;
import common.Relations;
import common.commands.CommandValue;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import javax.swing.ImageIcon;

import model.AltaRicaNode;
import parser.AltaRicaParseNode;
import parser.AltaRicaParser;
import parser.ParseException;
import ui.gui.documents.IconifiableItem;

public class Relation implements IconifiableItem {

    private String _id;
    private String _base;
    private Expression _expr;
    private AltaRicaNode _node;
    private AltaRicaModel _model;
    
    
    public Relation() {
    	
        this._id = null;
        this._base = null;
        this._expr = null;
        this._node = null;
    }

    public String getId() {
        return this._id;
    }

    public void setId(String id) {
        this._id = id;
    }

    public String getBase() {
        return this._base;
    }

    public void setBase(String base) {
        this._base = base;
    }

    public Expression getExpression() {
        return this._expr;
    }

    public void setExpression(Expression expr) {
        this._expr = expr;
    }

    public AltaRicaNode getNode() {
        return this._node;
    }

    public void setNode(AltaRicaNode node) {
        this._node = node;
    }

    @Override
    public String toString() {

        return _id + "( " + _base + " : " + _node.getName() + " ) := " + _expr.toString() + ";";
    }

    public static CommandValue parseRelation(String str, Relation r) {

        InputStream in = new ByteArrayInputStream(str.getBytes());

        try
        {
            r = AltaRicaParser.parseRelation(in);
        } catch (ParseException e) {
            System.out.println("Error");
            return CommandValue.KO;
        }

        AltaRicaParseNode pnode = new AltaRicaParseNode();
        pnode.compileRelation(r);
        r.setModel(AltaRicaModelManager.getCurrentModel());
        
        Relations.addRelation(r);

        return CommandValue.OK;
    }

	public void setModel(AltaRicaModel model) {
		this._model = model;
	}

	public AltaRicaModel getModel() {
		return this._model;
	}

	public ImageIcon getIcon() {
        return new javax.swing.ImageIcon(getClass().getResource("/resources/relation.png"));
    }
	
	
}
